﻿using Common.Identity;
using Common.Util;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Logging;
using Microsoft.Net.Http.Headers;

namespace Common.Filter;

public class AppActionFilter : IActionFilter
{
    private readonly ILogger<AppActionFilter> _logger;

    public AppActionFilter(ILogger<AppActionFilter> logger)
    {
        _logger = logger;
    }


    public void OnActionExecuting(ActionExecutingContext context)
    {
        _logger.LogInformation("App Action Filter Executing");
        var authorizationHeaderValues = context.HttpContext.Request.Headers[HeaderNames.Authorization];
        var value = authorizationHeaderValues.FirstOrDefault();
        if (string.IsNullOrWhiteSpace(value)) return;
        var token = value.Replace("Bearer ", "");
        try
        {
            var userInfo = TokenUtil.UnsafeDecode(token);
            userInfo.BearerToken = token;
            _logger.LogInformation("IdentityContext#Set: {@userInfo}", userInfo);
            IdentityContext.Set(userInfo);
        }
        catch (Exception e)
        {
            _logger.LogWarning("parse token error: {@error}", e.Message);
        }
    }

    public void OnActionExecuted(ActionExecutedContext context)
    {
        _logger.LogInformation("App Action Filter Executed");
        if (IdentityContext.Current == null) return;
        _logger.LogInformation("IdentityContext#Release: {@userInfo}",
            IdentityContext.Current);
        IdentityContext.Release();
    }
}